package com.shadow.study.java.base.util;

import com.shadow.study.common.constants.PunctuationConstants;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 没地方放的工具类.
 *
 * @author shadow
 * @since 2023
 * */
public final class CommonUtils {

    /** 未知的. */
    public static final String UNKNOWN = "unknown";

    private CommonUtils() {
    }

    /**
     * 获取登陆者ip.
     * @param request 请求
     * @return java.lang.String
     **/
    public static String getIpAddr(final HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(PunctuationConstants.SPLIT_COMMA).length > 1) {
            ip = ip.split(PunctuationConstants.SPLIT_COMMA)[0];
        }
        return ip;
    }
}
